let $body = $('body');
let $bar = $('<div></div>');
$body.append($bar);
let menubar = (function(){
  let active = -1,
      menus = [];
  let createMenuTitle = () => {
    let $titles = $('<ul class="titles"></ul>');
    menuData.map((item,i)=>{
      let $title = $('<li class="title"></li>');
      $title.html(item.title);
      $title.attr('data-id', i);
      let l = 54*(i);
      $title.css({left: l+'px'})
      $titles.append($title);

      $title.click(e=>{
        let i = Number(e.target.dataset.id);
        if (active === -1) {      
          menus[i].css({ display: 'inline-block' });
          active = i;
        } else if (active !== i) {
          menus[active].css({ display: 'none' });
          menus[i].css({display: 'inline-block'});
          active = i;
        } else {
          console.log('no');
          menus[active].css({display: 'none'});
          active = -1; 
        }
        e.stopPropagation();    
      });

      $title.hover(e=>{
        console.log(Number(e.target.dataset.id))
        if(active !== -1){
          let i = Number(e.target.dataset.id);
          menus[active].css({display: 'none'});
          menus[i].css({display: 'inline-block'});
          active = i;
        } 
      });
  })
  
    $bar.append($titles);
  }

  let createMenus = () => {
    menuData.map((item,i)=>{
      let $menus = $('<ul class="menus"></ul>');
      let items = item.menuItems; 
      $menus.css(item.css); 
      items.map((item)=>{
        if(item.title === 'hr'){
          let $hr = $('<li class="menu-hr"></li>');
          $menus.append($hr);
          return;
        }
        let $menu = $('<li class="menu-item"></li>');
        $menu.html(item.title);
        if(item.shortcut !== ''){
          let $shortcut = $('<span class="menu-shortcut"></span>');
          $shortcut.html(item.shortcut);
          $menu.append($shortcut);
        }
        let l = 54 * i;
        $menus.css({left: l+'px'})
        if(item.handler){
          $menu.click(item.handler)
        }
        $menus.append($menu);
      });

      $bar.append($menus);
      menus.push($menus);

    })

  }
  createMenuTitle();
  createMenus();
})();
